package com.hunlian.makelove.net;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

import com.hunlian.makelove.common.AppConfig;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 网络检测
 *
 */
public class NetTools {
	/**
	 * 返回当前网络是否可用
	 * 
	 * @param context
	 * @return
	 */
	public static boolean isConnect(Context context) {
		ConnectivityManager connectManager = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		if (connectManager == null)
			return false;
		NetworkInfo networkInfo = connectManager.getActiveNetworkInfo();
		return networkInfo == null || !networkInfo.isAvailable() ? false : true;
	}

	/**
	 * 返回网络类型
	 * 
	 * @param context
	 * @return -1：无网络、0：移动网络、1：WIFI other:未知网络
	 */
	public static int getNetworkType(Context context) {
		ConnectivityManager connectManager = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		if (connectManager == null)
			return -1;
		NetworkInfo networkInfo = connectManager.getActiveNetworkInfo();
		return networkInfo == null || !networkInfo.isAvailable() ? -1
				: networkInfo.getType();
	}

	/**
	 * 获取当前网络名称；
	 * 
	 * @param context
	 * @return
	 */
	public static String getNetworkTypeName(Context context) {
		String name = "无网络";
		ConnectivityManager manager = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		try {
			NetworkInfo activeNetInfo = manager.getActiveNetworkInfo();
			if (activeNetInfo != null && activeNetInfo.isAvailable()) {
				name = activeNetInfo.getExtraInfo();
			}
		} catch (Exception e) {
			return name;
		}
		return name;
	}

	/**
	 *获取网络时间
	 *@author zealjiang
	 *created at 2016/3/31 12:35
	 */
	public static void getNetTime(){

		Thread t = new Thread(){
			@Override
			public void run() {
				super.run();
				URL url;
				try {
					url = new URL("http://www.baidu.com");
					URLConnection uc = url.openConnection();// 生成连接对象
					uc.connect(); // 发出连接
					long ld = uc.getDate(); // 取得网站日期时间
					Date date = new Date(ld); // 转换为标准时间对象
					// 分别取得时间中的小时，分钟和秒，并输出
					SimpleDateFormat ss = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");//12小时制
					//System.out.println("时间： "+ss.format(date));
					AppConfig.netTime = ss.format(date);

				} catch (MalformedURLException e) {
					e.printStackTrace();
				}// 取得资源对象
				catch (IOException e) {
					e.printStackTrace();
				}
			}
		};
		t.start();

	}




}
